package com.qf.myrbac.annotation;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.myrbac.sys.entity.SysLog;
import com.qf.myrbac.sys.service.SysLogService;
import com.qf.myrbac.sys.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class OperationLogAspect {
    @Autowired
    private SysLogService logService;

    @Pointcut("@annotation(com.qf.myrbac.annotation.OperationLog)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        long start = new Date().getTime();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        OperationLog operationLog = method.getAnnotation(OperationLog.class);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long userId = user.getUserId();
        String username = user.getUsername();
        String optName = operationLog.optName();
        ObjectMapper objectMapper = new ObjectMapper();
        String arg = objectMapper.writeValueAsString(pjp.getArgs()[0]);
        SysLog log = new SysLog(null, userId, username, new Date(), optName, arg);
        logService.save(log);
        pjp.proceed();
        long end = new Date().getTime();
        System.out.println("耗时：" + (end - start) + "毫秒");
    }
}
